# -*- encoding:utf8 -*-
import os.path
from django.shortcuts import render,redirect
from django.http import HttpResponse
# import json
from tool_func import jsonpost
import attend
import ajax
# from ajax import ajax_hr,ajax_wx
import login
import weixin
from django.http import Http404
from django.template.base import TemplateDoesNotExist
from django.utils import timezone
import io
import json
import excel
import convert
from models import AvaiLeave,StaffInfo
from tool_func import get_or_none
from datetime import datetime
from django.core.urlresolvers import reverse
import leave

# def index(req):
    # return render(req, 'index.html', {})

def hr_shortcut_index(request):
    """测试用，快捷登录，跳转到index
    """
    request.session['empid']='AE1856'
    return redirect(reverse('hr',args=['index']))

def setcmd(request):
    """
    测试时，用于方便的设置当前操作的员工。
    例如设置AE1856为当前操作员工
    /attendance/setcmd?empid=AE1856
    
    """
    empid=request.GET.get('empid')
    request.session['empid']=empid
    return HttpResponse('ok empid= %s'%empid)


def ajax_view(request):
    """
    所有静态页面获取数据都走这里。
    """
    return jsonpost(request, ajax.get_global())

def test(request):
    #rt =weixin.send_text('AE1856','hello my friends')
    #return HttpResponse('ok')
    txt='hello world'
    rs=HttpResponse(txt)
    rs['Content-type']='text/plain'
    rs['Content-Disposition'] = 'attachment; filename="haha.txt"'
    return rs


def get_excel(request):
    """
    head:[{name:'empid',label:'员工号'},{name:'time',label:'时间'}]
    data:[{'empid':'AE1856','time:'2015-10-01'},{}]
    """
    data=json.loads(request.POST.get('data'))
    heads=json.loads(request.POST.get('heads',[]))
    ls=[]
    order=[]
    if heads:
        rowls=[]
        for h in heads:
            order.append(h.get('name'))
            rowls.append(h.get('label'))
        ls.append(rowls)
            
    for row in data:
        rowls=[]
        if not order:
            for k in row:
                order.append(k)
                rowls.append(row.get(k))
        else:
            for name in order:
                rowls.append(row.get(name))
        ls.append(rowls)
    # txt='hello world'
    exceldata=excel.list2excel07(ls)
    rs=HttpResponse(exceldata)
    rs['Content-type']= 'application/octet-stream' # 'text/plain'
    rs['Content-Disposition'] = 'attachment; filename="exported.xlsx"'
    return rs

def weixin_pages(request,page):
    """
    所有微信页面
    """
    # 如果有code，证明是微信认证跳转过来的。把code转换为用户id存在cookies里面
    code = request.GET.get('code')
    if code:
        userid =weixin.userid_from_code(code)
        request.session['empid']=userid
        if not userid:
            return HttpResponse('you are not employee')
        
    # 从cookies里面取用户id
    staff=login.get_user(request)
    if not staff:
        abspath = request.META.get('HTTP_HOST')+request.path
        url = weixin.embed_url(abspath)
        return redirect(url)
    # empid = request.session.get('empid', '')
    # return HttpResponse('empid is %s'%empid)
    if not page.endswith('.html'):
        page='weixin/%s.html'%page
    else:
        page='weixin/%s'%page
    try:
        return  render(request,page)
    except TemplateDoesNotExist:
        raise Http404("url does not exist %s"%page)
    


def hr_pages(request,page):
    """
    HR操作的页面
    """
    if not page.endswith('.html'):
        page='web_pages/%s.html'%page
    else:
        page='web_pages/%s'%page
    return render(request,page)    
    


def upload_attend_record(request):
    """导入原始考勤记录
    """
    byt=io.BytesIO()
    f = request.FILES['file']
    for i in f.chunks():
        byt.write(i)
        
    attend.input_excel( file_contents=byt.getvalue())
    rt=  {'status':'success'}
    return HttpResponse(json.dumps(rt), content_type="application/json")

def upload_leave_data(request):
    if request.method=='POST':
        byt=io.BytesIO()
        f = request.FILES['file']
        for i in f.chunks():
            byt.write(i)   
        success_dict=leave.import_leaves(file_contents=byt.getvalue())
        return HttpResponse(json.dumps(success_dict), content_type="application/json")
    
def upload_avai_leave(request):
    """导入可用假期
    """
    byt=io.BytesIO()
    f = request.FILES['file']
    for i in f.chunks():
        byt.write(i)
    filecontent=byt.getvalue()
    ls=excel.excel07_2list(filecontent)
    kw=['empid','category','date','length']
    head = ls[0]
    hd={'empid':head.index('empid'),
        'category':head.index('category'),
        'date':head.index('date'),
        'length':head.index('length')
        }
    msgs=[]
    for row in ls[1:]:
        staff=get_or_none(StaffInfo,employee_id=row[hd['empid']])
        if not staff:
            msgs.append('%s not exsit'%row[hd['empid']])
            continue
        thatdate=row[hd['date']]
        if isinstance(thatdate,(str,unicode)):
            thatdate=datetime.strptime(thatdate,'%Y/%m/%d').date()
        start_date=convert.date2str(thatdate)
        this_year='%s-01-01'%timezone.now().year
        category=row[hd['category']]
        length=row[hd['length']]         
        avai,creatd=AvaiLeave.objects.get_or_create(staff=staff,category=category,start_date=start_date)
        if category=='swap_off':
            length=int(float(length)*60)     # 调休单位是小时
        else:
            length=int(float(length)*8*60)   # 其他单位是天
        if category=='annual_leave' and start_date==this_year:
            avai.used=convert.i2t(-length)
        else:
            avai.span=convert.i2t(length)
        avai.save()
    if msgs:
        rt={'status':'fail','msg':msgs}
    else:
        rt={'status':'success'}
    return HttpResponse(json.dumps(rt), content_type="application/json")        


            

    